package com.herui.iot.ui.evaluation.execute;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.github.mikephil.charting.charts.LineChart;
import com.herui.device_lib.presenter.DevicePresenterInter;
import com.herui.device_lib.treadmill.tp.body.EcgBody;
import com.herui.device_lib.treadmill.tp.body.HeartRateDataBody;
import com.herui.device_lib.treadmill.tp.body.TreadmillDataBody;
import com.herui.sdyu_lib.base.FragmentDirectionAnim;
import com.herui.sdyu_lib.utils.ToastUtil;
import com.herui.sport_care.R;
import com.herui.sport_care.config.AppConfig;
import com.herui.sport_care.data.SimDataFactory;
import com.herui.sport_care.data.check.AgreementResponse;
import com.herui.sport_care.data.check.DeviceInfo;
import com.herui.sport_care.data.check.EquipmentType;
import com.herui.sport_care.data.check.EvalUserInfo;
import com.herui.sport_care.data.check.EvaluationStage;
import com.herui.sport_care.data.eval.EvalInfo;
import com.herui.sport_care.ui.BaseSportFragment;
import com.herui.sport_care.ui.dialog.PopDialog;
import com.herui.sport_care.ui.view.PoweLineChartView;
import com.herui.sport_care.ui.view.TreadmillLineChartView;
import com.herui.sport_care.utils.DateUtils;
import com.proton.view.EcgRealTimeView;

import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 跑台实验
 */
public class TreadmillExecuteFragment extends BaseSportFragment {

    @BindView(R.id.view_user)
    View view_user;
    @BindView(R.id.view_device)
    View view_device;
    @BindView(R.id.tv_user)
    TextView tv_user;
    @BindView(R.id.tv_ecg)
    TextView tv_ecg;

    @BindView(R.id.id_ecg_view)
    EcgRealTimeView id_ecg_view;

    @BindView(R.id.mDoubleLineChar)
    LineChart mDoubleLineChar;
    TreadmillLineChartView powerLineChartView;

    @BindView(R.id.tv_calorie)
    TextView tv_calorie;
    @BindView(R.id.tv_heart)
    TextView tv_heart;
    @BindView(R.id.tv_distance)
    TextView tv_distance;
    @BindView(R.id.tv_slope)
    TextView tv_slope;
    @BindView(R.id.tv_speed)
    TextView tv_speed;

    @BindView(R.id.tv_time)
    TextView tv_time;
    @BindView(R.id.tv_agreement)
    TextView tv_agreement;
    @BindView(R.id.btn_control)
    Button btn_control;

    @BindView(R.id.view_recover_detect)
    View view_recover_detect;

    private RecoverDetectView recoverDetectView;

    private Long evaluationSchemeId;
    private EvalInfo evalInfo;

    // 被选择的心电设备 在静息的时候选择的
    private DeviceInfo ecgDeviceInfo;
    // 被选择的用户
    private EvalUserInfo evalUserInfo;
    // 被选择的踏车设备
    private DeviceInfo treadmillDeviceInfo;

    private ExecteServerPresenter execteServerPresenter;
    private DevicePresenterInter devicePresenter;
    private TreadmillExecutePresenter executePresenter;

    public TreadmillExecuteFragment(EvalInfo evalInfo, DeviceInfo ecgDeviceInfo) {
        this.evalInfo = evalInfo;
        this.ecgDeviceInfo = ecgDeviceInfo;
        evaluationSchemeId = evalInfo.getEvaluationSchemeId();
        execteServerPresenter = new ExecteServerPresenter(view);
    }

    public static TreadmillExecuteFragment newInstance(EvalInfo evalInfo,
                                                       DeviceInfo ecgDeviceInfo) {
        TreadmillExecuteFragment fragment = new TreadmillExecuteFragment(evalInfo, ecgDeviceInfo);
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);

        executePresenter = new TreadmillExecutePresenter(executeView, evalInfo);
        executePresenter.setEcgDeviceInfo(ecgDeviceInfo);
        devicePresenter = executePresenter.getDevicePresenter();

        recoverDetectView = new RecoverDetectView(view_recover_detect);
        recoverDetectView.initUI(baseActivity, devicePresenter, executePresenter);

        executePresenter.start();

        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        executePresenter.stop();
    }

    @Override
    public int getLayout() {
        return R.layout.fragment_treadmill_execute;
    }

    @Override
    public void initParam() {
        view_recover_detect.setVisibility(View.GONE);
        // 连接心电设备
        devicePresenter.connectEcg(ecgDeviceInfo.getMac());

        powerLineChartView = new TreadmillLineChartView(mDoubleLineChar);
        powerLineChartView.init();
        if (AppConfig.DeviceDebug) {
            simData();
        }
    }

    private void simData() {
        evalUserInfo = SimDataFactory.getEvalUserInfo();
        tv_user.setText(evalUserInfo.getName());
        executePresenter.setEvalUserInfo(evalUserInfo);
    }

    @OnClick({R.id.btn_control, R.id.view_user, R.id.view_device})
    public void onViewClick(View view) {
        switch (view.getId()) {
            case R.id.btn_control:
                // 控制流程
                // 控制流程
                if (evalUserInfo == null) {
                    ToastUtil.showMessage("请先选择用户");
                    return;
                }
                executePresenter.next();
//                add(AskQuesFragment.newInstance(evalInfo), new FragmentDirectionAnim());
                break;
            case R.id.view_user:
                // 查询用户列表
                execteServerPresenter.findAwaitItemList(evaluationSchemeId, 1);
                break;
            case R.id.view_device:
                // 查询可用心电设备列表
                if (evalUserInfo == null) {
                    ToastUtil.showMessage("请先选择用户");
                    return;
                }
                execteServerPresenter.getAvailableEquipmentList(evaluationSchemeId,
                        evalUserInfo.getUserId(), EquipmentType.TREADMILL);
                break;
        }
    }


    TreadmillExecutePresenter.View executeView = new TreadmillExecutePresenter.View() {

        @Override
        public void finish() {
            add(AskQuesFragment.newInstance(evalInfo), new FragmentDirectionAnim());
//            baseActivity.runOnUiThread(new Runnable() {
//                @Override
//                public void run() {
//                    baseActivity.onBackPressed();
//                }
//            });
        }

        @Override
        public void onStage(EvaluationStage stage) {
            baseActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    powerLineChartView.clear();
                    switch (stage) {
                        case WARM_UP:
                            btn_control.setText("开始测试");
                            break;
                        case TESTING:
                            btn_control.setText("恢复测试");
                            break;
                        case RECOVER:
                            view_recover_detect.setVisibility(View.VISIBLE);
                            btn_control.setText("结束测试");
                            break;
                    }
                }
            });
        }

        @Override
        public void onTime(int second) {
            baseActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    tv_time.setText(DateUtils.sToHHmmss(second));
                }
            });
        }

        @Override
        public void onAgreementResponse(AgreementResponse agreementResponse) {
            tv_agreement.setText(agreementResponse.getName());
        }

        @Override
        public void onTreadmillDataBody(TreadmillDataBody treadmillDataBody) {
            Double slope = treadmillDataBody.getSlope();
            Long calorie = treadmillDataBody.getCalorie();
            Long totalDistance = treadmillDataBody.getTotalDistance();
            Double sped = treadmillDataBody.getSped();

            tv_calorie.setText(calorie + "");
            tv_distance.setText(totalDistance + "");
            tv_slope.setText(slope + "");
            tv_speed.setText(sped + "");

            powerLineChartView.addData(calorie, sped.floatValue());
        }

        @Override
        public void onConnectEcg(boolean flag) {
            if (flag) {
                ToastUtil.showMessage("心电连接成功");
            } else {
                ToastUtil.showMessage("心电连接失败");
            }
        }

        @Override
        public void onConnectSpo(boolean flag) {
            recoverDetectView.onConnectSpo(flag);
            if (flag) {
                ToastUtil.showMessage("血氧连接成功");
            } else {
                ToastUtil.showMessage("血氧连接失败");
            }
        }

        @Override
        public void onEcgBody(EcgBody ecgBody) {
            byte[] data = ecgBody.getEcgData();
//            id_ecg_view.addEcgData(data);
        }

        @Override
        public void onHeartRateDataBody(HeartRateDataBody heartRateDataBody) {

            Integer heart = heartRateDataBody.getHeartRate();
            if (heart < 0) {
                tv_heart.setText("--");
                return;
            }
            tv_heart.setText(heart + "");
        }
    };

    ExecteServerPresenter.View view = new ExecteServerPresenter.View() {

        @Override
        public void onEvalUserInfo(List<EvalUserInfo> evalUserInfos) {
            if (evalUserInfos.size() == 0){
                ToastUtil.showMessage("未获取到用户");
                return;
            }
            List<String> collect = new LinkedList<>();
            for (EvalUserInfo evalUserInfo : evalUserInfos) {
                collect.add(evalUserInfo.getName());
            }

            new PopDialog(baseActivity, view_user, R.layout.item_pop_eval_value,
                    collect, "", new PopDialog.SelectLis() {
                @Override
                public void onSelect(String value) {
                    for (EvalUserInfo evalUserInfo1 : evalUserInfos) {
                        if (evalUserInfo1.getName().equals(value)) {
                            evalUserInfo = evalUserInfo1;
                            tv_user.setText(evalUserInfo.getName());
                            executePresenter.setEvalUserInfo(evalUserInfo1);
                            break;
                        }
                    }
                }
            });
        }

        @Override
        public void onDeviceInfo(List<DeviceInfo> deviceInfos) {
            if (deviceInfos.size() == 0){
                ToastUtil.showMessage("未获取到跑步机设备");
                return;
            }
            List<String> collect = new LinkedList<>();
            for (DeviceInfo evalUserInfo : deviceInfos) {
                collect.add(evalUserInfo.getEquipmentName());
            }

            new PopDialog(baseActivity, view_device, R.layout.item_pop_eval_value,
                    collect, "", new PopDialog.SelectLis() {
                @Override
                public void onSelect(String value) {
                    for (DeviceInfo deviceInfo : deviceInfos) {
                        if (deviceInfo.getEquipmentName().equals(value)) {
                            tv_ecg.setText(deviceInfo.getEquipmentName());
                            executePresenter.setTreadmillDeviceInfo(deviceInfo);
                            break;
                        }
                    }
                }
            });
        }
    };

}